import { ref, onMounted, inject } from "vue";
import { getProductDetail } from "@/api/modules/agv";
import { useDict } from "@/hooks/useDict";
import { generateUUID } from "@/utils";
import { getListAllUser } from "@/api/modules/sys";

const setInfo = (data: string | Array<any>) => {
  if (Array.isArray(data)) {
    data = data.length ? data : "";
  }
  return data || "--";
};
const transformData = (originData: any, initData: any, urlResource: string | undefined, getDictItem: any, listAllUser: any) => {
  const basicInfo: any = {
    mapping: {
      type: getDictItem("productId", originData["type"]),
      nonStandard: originData["nonStandard"] ? "是" : "否",
      nonStandardCycle: originData["nonStandardCycle"]
        ? setInfo(originData["nonStandardCycle"]) + "天"
        : setInfo(originData["nonStandardCycle"])
    },
    content: {
      type: "产品类型",
      productCategoryName: "产品型号",
      projectName: "所属项目",
      projectCode: "项目编号",
      productionTime: "出厂时间",
      nonStandard: "非标定制",
      nonStandardCycle: "定制周期",
      nonStandardContent: "定制项"
    }
  };
  const statusInfo: any = {
    mapping: {
      state: getDictItem("vehicleStatus", originData["state"]),
      lockState: setInfo(originData["lockState"]) === "--" ? "--" : originData["lockState"] ? "已锁车" : "未锁车"
    },
    content: {
      deviceHwVersion: "仪表硬件版本",
      deviceSwVersion: "仪表软件版本",
      lockState: "车辆锁车状态",
      state: "车辆状态",
      hdop: "水平精度",
      gpsCollectTime: "GPS采集时间",
      latitude: "纬度",
      longitude: "经度",
      onlineTime: "上线时间",
      offlineTime: "下线时间"
    }
  };

  const mainInfo: any = {
    mapping: {},
    content: {
      code: "车架号",
      deviceId: "仪表ID",
      controllerId: "主控ID",
      hydroCylinderCode: "油缸编号",
      driveMotorCode: "驱动电机编号",
      steeringMotorCode: "转向电机编号",
      pumpMotorCode: "泵电机编号",
      pumpControllerCode: "泵控制器编号",
      wheelControllerCode: "轮控制器编号",
      standardForkSpacing: "标准货叉外间距（mm）",
      steeringControllerCode: "转向控制器编号",
      laserCode: "激光编号",
      aeArEmptyFrontWheelLoad: "前轮载荷（AE/AR 空载 ）",
      aeArEmptyRearWheelLoad: "后轮载荷（AE/AR 空载）",
      aeArFullFrontWheelLoad: "前轮载荷（AE/AR 全载）",
      aeArFullRearWheelLoad: "后轮载荷（AE/AR 全载）"
    }
  };

  const batteryInfo: any = {
    mapping: {
      batteryNameplate: originData["batteryNameplate"] ? urlResource + originData["batteryNameplate"] : ""
    },
    content: {
      batterySerialCode: "电池序列号",
      batteryNameplate: "电池铭牌信息"
    }
  };

  const otherInfo: any = {
    mapping: {},
    content: {
      other: "非标及其他信息"
    }
  };
  const options: any = {
    // 基本信息
    1: (item: any, originData: any) => {
      const keys = Object.keys(basicInfo.mapping);
      for (const [key, value] of Object.entries(basicInfo.content)) {
        if (keys.includes(key)) {
          item.children.push({
            title: value,
            value: setInfo(basicInfo.mapping[key])
          });
        } else {
          item.children.push({
            title: value,
            value: setInfo(originData[key])
          });
        }
      }
    },
    // 车辆图片
    2: (item: any, originData: any) => {
      originData.productDataList.forEach((itm: any) => {
        if (itm.type === 1) {
          item.children.push({
            path: urlResource + itm.path,
            remark: itm.remark
          });
        }
      });
    },
    // 车辆状态信息
    3: (item: any, originData: any) => {
      const keys = Object.keys(statusInfo.mapping);
      for (const [key, value] of Object.entries(statusInfo.content)) {
        if (keys.includes(key)) {
          item.children.push({
            title: value,
            value: setInfo(statusInfo.mapping[key])
          });
        } else {
          item.children.push({
            title: value,
            value: setInfo(originData[key])
          });
        }
      }
      item.lng = originData.longitude;
      item.lat = originData.latitude;
    },
    // 主体信息
    4: (item: any, originData: any) => {
      const keys = Object.keys(mainInfo.mapping);
      for (const [key, value] of Object.entries(mainInfo.content)) {
        if (keys.includes(key)) {
          item.children.push({
            title: value,
            value: setInfo(mainInfo.mapping[key])
          });
        } else {
          item.children.push({
            title: value,
            value: setInfo(originData[key])
          });
        }
      }
      // 激光信息
      originData.oaLaserCodeList &&
        originData.oaLaserCodeList.forEach((itm: any, index: number) => {
          item.children.push({
            title: `避障激光${index + 1}编号`,
            value: setInfo(itm.code)
          });
        });
    },
    // 电池信息
    5: (item: any, originData: any) => {
      const keys = Object.keys(batteryInfo.mapping);
      for (const [key, value] of Object.entries(batteryInfo.content)) {
        if (keys.includes(key)) {
          item.children.push({
            title: value,
            type: key === "batteryNameplate",
            value: setInfo(batteryInfo.mapping[key])
          });
        } else {
          item.children.push({
            title: value,
            value: setInfo(originData[key])
          });
        }
      }
    },
    // 测试信息
    6: (item: any, originData: any) => {
      originData.productDataList.forEach((itm: any) => {
        if (itm.type === 2) {
          item.children.push({
            path: urlResource + itm.path,
            remark: itm.remark
          });
        }
      });
    },
    // 其他信息
    7: (item: any, originData: any) => {
      originData.productDataList.forEach((itm: any) => {
        if (itm.type === 3) {
          item.children.push({
            path: urlResource + itm.path,
            remark: itm.remark
          });
        }
      });
    },
    9: (item: any, originData: any) => {
      for (const [key, value] of Object.entries(otherInfo.content)) {
        item.children.push({
          title: value,
          value: setInfo(originData[key])
        });
      }
    },
    8: (item: any, originData: any) => {
      originData.assemblyInfos.forEach((itm: any) => {
        const user = listAllUser.value.find(it => it.id === itm.userId);
        item.children.push({
          title: itm.assemblyItem,
          value: (user && user.name) || "--"
        });
      });
    }
  };
  // 开始处理
  initData.forEach((item: any) => {
    options[item.type](item, originData);
  });
  return initData;
};

export const useDetail = (options: any) => {
  const urlResource: string | undefined = inject("urlResource");
  const { getDictItem } = useDict(["vehicleStatus", "productId"]);

  const { id } = options;
  const detailData: any = ref({});
  const listAllUser: any = ref([]);
  const initData = [
    {
      name: "基本信息",
      id: generateUUID(),
      type: 1,
      children: []
    },
    {
      name: "车辆外观",
      id: generateUUID(),
      type: 2,
      children: []
    },
    {
      name: "车辆状态信息",
      id: generateUUID(),
      type: 3,
      children: []
    },
    {
      name: "本体信息",
      id: generateUUID(),
      type: 4,
      children: []
    },
    {
      name: "电池信息",
      id: generateUUID(),
      type: 5,
      children: []
    },
    {
      name: "装配信息",
      id: generateUUID(),
      type: 8,
      children: []
    },
    {
      name: "测试视频",
      id: generateUUID(),
      type: 6,
      children: []
    },
    {
      name: "其他信息",
      id: generateUUID(),
      type: 7,
      children: []
    },
    {
      name: "非标及定制信息",
      id: generateUUID(),
      type: 9,
      children: []
    }
  ];
  const getDetail = async (id: number) => {
    await getListAllUserFn();
    const { data } = await getProductDetail({ id });
    const result = transformData(data, initData, urlResource, getDictItem, listAllUser);
    detailData.value = result;
  };
  // 获取全部用户
  const getListAllUserFn = async () => {
    const { data } = await getListAllUser();
    listAllUser.value = data;
  };
  onMounted(() => {
    getDetail(id);
  });
  return {
    detailData
  };
};
